package com.zjzaki.thingsboard.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * 用于检测是否能与服务器通信
 */
public class Ping {

    /**
     * ping命令去检测是否可以与服务器通信
     * @param address 服务器地址
     * @param pingTimes 检测次数
     * @param timeOut 超时时间
     * @return 是否能连接
     */
    public static boolean ping(String address, int pingTimes, int timeOut) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("ping " + "-c " + pingTimes + " -w " + timeOut + " " + address);
            InputStreamReader r = new InputStreamReader(process.getInputStream());
            LineNumberReader returnData = new LineNumberReader(r);

            String returnMsg = "";

            String line = "";

            while ((line = returnData.readLine()) != null) {
                System.out.println(line);
                returnMsg += line;

            }
            if (returnMsg.indexOf("100% packet loss") != -1) {
//                System.out.println("与 " + address + " 连接不畅通.");
                return false;
            } else {
//                System.out.println("与 " + address + " 连接畅通.");
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
